package kr.nexmore.slmsample2.view.widgetsample;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import kr.nexmore.slmsample2.uri.Part_Uri;
import kr.nexmore.slmsample2.uri.Preference_Uri;
import kr.nexmore.slmsample2.validation.LengthValidator;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.di.extensions.Preference;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.internal.services.Activator;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.e4.ui.workbench.UIEvents;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.IWindowCloseHandler;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.osgi.service.prefs.BackingStoreException;

public class CheckPart implements SelectionListener, Listener, IWindowCloseHandler {

	@Inject
	@Preference(nodePath = Preference_Uri.CHECKPART_NODEPATH, value = Preference_Uri.CHECKPART_VALUE_CHECK_1)
	private Boolean check_1;

	@Inject
	@Preference(nodePath = Preference_Uri.CHECKPART_NODEPATH, value = Preference_Uri.CHECKPART_VALUE_CHECK_2)
	private Boolean check_2;

	@SuppressWarnings("restriction")
	@Inject
	@Preference(nodePath = Preference_Uri.CHECKPART_NODEPATH, value = Preference_Uri.CHECKPART_VALUE_CHECK_3)
	private Boolean check_3;

	@Inject
	@Preference(nodePath = Preference_Uri.CHECKPART_NODEPATH)
	private IEclipsePreferences prfes;

	private Composite composite;

	private MWindow mWindow;

	private List list;
	
	@Inject
	private IWorkbench iWorkbench;

	public CheckPart() {
	}

	/**
	 * Create contents of the view part.
	 */
	@PostConstruct
	public void createControls(Composite parent) {
		composite = parent;

		final Shell shell = new Shell(composite.getDisplay());

		/*
		 * mWindow. shell.addListener(SWT.CLOSE,this);
		 * parent.getParent().addListener(SWT.CLOSE,this);
		 * composite.addListener(SWT.CLOSE,this);
		 * composite.getShell().addListener(SWT.CLOSE,this);
		 */

		parent.setLayout(null);

		Button btnCheckButton = new Button(parent, SWT.CHECK);
		btnCheckButton.addSelectionListener(this);
		btnCheckButton.setBounds(10, 30, 94, 16);
		btnCheckButton.setText("check_1");
		btnCheckButton.setSelection(check_1);

		Button btnCheckButton_1 = new Button(parent, SWT.CHECK);
		btnCheckButton_1.addSelectionListener(this);
		btnCheckButton_1.setBounds(10, 63, 94, 16);
		btnCheckButton_1.setText("check_2");
		btnCheckButton_1.setSelection(check_2);

		Button btnCheckButton_2 = new Button(parent, SWT.CHECK);
		btnCheckButton_2.addSelectionListener(this);
		btnCheckButton_2.setBounds(10, 101, 94, 16);
		btnCheckButton_2.setText("check_3");
		btnCheckButton_2.setSelection(check_3);

		ListViewer listViewer = new ListViewer(parent, SWT.BORDER | SWT.V_SCROLL);
		list = listViewer.getList();
		list.setBounds(265, 84, 233, 315);

		Button btnNewButton = new Button(parent, SWT.NONE);
		btnNewButton.setText("InputDialog");
		btnNewButton.setBounds(10, 177, 76, 25);
		btnNewButton.addSelectionListener(this);

		Button btnMessagedialog = new Button(parent, SWT.NONE);
		btnMessagedialog.setText("MessageDialog\u200B");
		btnMessagedialog.setBounds(112, 177, 76, 25);
		btnMessagedialog.addSelectionListener(this);

		Button btnProgressMonitorDialog = new Button(parent, SWT.NONE);
		btnProgressMonitorDialog.setText("ProgressMonitorDialog");
		btnProgressMonitorDialog.setBounds(10, 227, 76, 25);
		btnProgressMonitorDialog.addSelectionListener(this);

		Button btnErrordialog = new Button(parent, SWT.NONE);
		btnErrordialog.setText("ErrorDialog");
		btnErrordialog.setBounds(112, 227, 76, 25);
		btnErrordialog.addSelectionListener(this);

	}

	@Inject
	@Optional
	public void startupComplete(@UIEventTopic(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE) MApplication application, EModelService modelService) {
		MWindow window = (MWindow) modelService.find(Part_Uri.WINDOW_MAIN, application);
		window.getContext().set(IWindowCloseHandler.class, this);
	}

	/**
	 * 클릭 이벤트
	 */
	@Override
	public void widgetSelected(SelectionEvent e) {
		// TODO Auto-generated method stub

		Button btn = (Button) e.widget;
		Boolean checked;

		switch (btn.getText()) {
		case "check_1":
			checked = ((Button) e.getSource()).getSelection();
			prfes.putBoolean(Preference_Uri.CHECKPART_VALUE_CHECK_1, checked);

			break;
		case "check_2":
			checked = ((Button) e.getSource()).getSelection();
			prfes.putBoolean(Preference_Uri.CHECKPART_VALUE_CHECK_2, checked);

			break;
		case "check_3":
			checked = ((Button) e.getSource()).getSelection();
			prfes.putBoolean(Preference_Uri.CHECKPART_VALUE_CHECK_3, checked);

			break;

		case "체크박스":
			break;
		case "리스트":
			break;
		case "InputDialog":

			InputDialog dialog = new InputDialog(composite.getShell(), "타이트", "메시지", "", new LengthValidator());
			if (dialog.open() == Window.OK) {
				// User clicked OK; update the label with the input
				list.add(dialog.getValue());
			}
			break;
		case "ErrorDialog":

			showException(new ClassNotFoundException());
			break;
		case "MessageDialog​":

			MessageDialog.openWarning(composite.getShell(), "Warning", "메시지");
			// MessageDialog.openError(composite.getShell(), "Error", "메시지");
			break;
		case "ProgressMonitorDialog":
			try {
				new ProgressMonitorDialog(composite.getShell()).run(true, true, new LongRunningOperation(true));
			} catch (InvocationTargetException | InterruptedException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}

			break;

		default:
			break;

		}
		try {
			prfes.flush();
		} catch (BackingStoreException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub

	}

	/**
	 * x버튼 누를때
	 */
	@Override
	public void handleEvent(Event event) {
		int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO;
		MessageBox messageBox = new MessageBox(composite.getShell(), style);
		messageBox.setText("Information");
		messageBox.setMessage("Close the shell?");
		event.doit = messageBox.open() == SWT.YES;

	}

	@Override
	public boolean close(MWindow window) {
		// TODO Auto-generated method stub
		int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO;
		MessageBox messageBox = new MessageBox(composite.getShell(), style);
		messageBox.setText("Information");
		messageBox.setMessage("종료하시겠습니까?");
		int i = messageBox.open();
		switch (i) {
		case SWT.YES:
			
			iWorkbench.close();
			break;
		case SWT.NO:

			break;

		default:
			break;
		}
		// event.doit = messageBox.open() == SWT.YES;
		return false;
	}

	/**
	 * 익셉션 다이얼로그
	 * 
	 * @param ex
	 */
	public void showException(final Exception ex) {
		Display.getDefault().syncExec(new Runnable() {
			@Override
			public void run() {
				StringWriter sw = new StringWriter();
				ex.printStackTrace(new PrintWriter(sw));
				IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), new Exception(sw.toString()));
				ErrorDialog.openError(Display.getDefault().getActiveShell(), "Error", ex.toString(), status);
			}
		});
	}
}

class LongRunningOperation implements IRunnableWithProgress {
	// The total sleep time
	private static final int TOTAL_TIME = 10000;

	// The increment sleep time
	private static final int INCREMENT = 500;

	private boolean indeterminate;

	/**
	 * LongRunningOperation constructor
	 * 
	 * @param indeterminate
	 *            whether the animation is unknown
	 */
	public LongRunningOperation(boolean indeterminate) {
		this.indeterminate = indeterminate;
	}

	/**
	 * Runs the long running operation
	 * 
	 * @param monitor
	 *            the progress monitor
	 */
	public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
		monitor.beginTask("Running long running operation", indeterminate ? IProgressMonitor.UNKNOWN : TOTAL_TIME);
		for (int total = 0; total < TOTAL_TIME && !monitor.isCanceled(); total += INCREMENT) {
			Thread.sleep(INCREMENT);
			monitor.worked(INCREMENT);
			if (total == TOTAL_TIME / 2)
				monitor.subTask("Doing second half");
		}
		monitor.done();
		if (monitor.isCanceled())
			throw new InterruptedException("The long running operation was cancelled");
	}
}
